package video;

import net.cl.Validator;
import net.cl.tools.json.JsonArray;
import net.cl.tools.json.JsonObject;
import net.cl.utils.HttpUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * @author CaoLei
 * 
 */
public class Letv {

	private static final Log log = LogFactory.getLog(Letv.class);
	private static final String INDEX_PREFIX2 = "http://app.letv.com/v.php?id=";
	private static final String VIDEO_URL = "http://www.letv.com/ptv/vplay/%s.html";
	private static final String ENCODE = "UTF-8";

	public Letv() {
	}

	public String getVideoSource(String videoKey) {
		String indexUrl = INDEX_PREFIX2 + videoKey;
		try {
			String html = HttpUtil.getResponseString(indexUrl);
			Document document = DocumentHelper.parseText(html);
			JsonObject jsonObj = null;

			Element e = document.getRootElement().element("error_msg");
			if (e != null && Validator.isNotEmpty(e.getText()))
				System.out.println(e.getTextTrim());
			else {
				e = document.getRootElement().element("mmsJson");
				jsonObj = JsonObject.fromString(e.getText().replace("\\", ""));
			}
			StringBuilder sb = new StringBuilder();
			JsonArray jsonArray = jsonObj.getJsonObject("bean").getJsonArray("video");
			for (int i = 0; i < jsonArray.size(); i++) {
				try {
					jsonObj = jsonArray.getJsonObject(i);
					jsonObj = JsonObject.fromString(HttpUtil.getResponseString(jsonObj.getString("url")));
					if (sb.length() > 0)
						sb.append("[=]");
					sb.append(jsonObj.getString("location"));
				} catch (Exception e1) {
					log.error(e1);
				}
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		Letv letv = new Letv();
		System.out.println(letv.getVideoSource("822277"));
	}

}
